﻿using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Seagull.Configuration.ConfigSaver
{
    public class XmlConfigSaver : IConfigSaver
    {
        private static readonly XmlWriterSettings _xmlWriterSettings = new XmlWriterSettings
        {
            NewLineHandling = NewLineHandling.None,
            Indent = true,
            NewLineOnAttributes = true
        };

        public TConfig Load<TConfig>(string filename)
        {
            var serializer = new XmlSerializer(typeof(TConfig));
            using(var stream = File.OpenRead(filename))
            {
                var config = (TConfig)serializer.Deserialize(stream);
                return config;
            }
        }

        public void Save<TConfig>(TConfig config, string filename)
        {
            var serializer = new XmlSerializer(typeof(TConfig));
            using(var fileStream = File.Open(filename, FileMode.Create, FileAccess.Write))
            {
                using(var writer = XmlWriter.Create(fileStream, _xmlWriterSettings))
                {
                    serializer.Serialize(writer, config);
                }
            }
        }
    }
}
